package com.rfid.web.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.rfid.common.exception.BusinessException;
import com.rfid.common.utils.CacheUtils;
import com.rfid.common.utils.ShiroUtils;
import com.rfid.common.utils.StringUtils;
import com.rfid.framework.web.domain.server.Sys;
import com.rfid.framework.web.service.CodeGenerateService;
import com.rfid.system.domain.TCustomerInfo;
import com.rfid.system.domain.TItemInfo;
import com.rfid.system.domain.TProductInfo;
import com.rfid.system.domain.TProductOrderTotal;
import com.rfid.system.service.ITIteminfoService;
import com.rfid.system.service.ITProductInfoService;
import com.rfid.system.service.ITProductOrderTotalService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rfid.common.annotation.Log;
import com.rfid.common.enums.BusinessType;
import com.rfid.common.core.controller.BaseController;
import com.rfid.common.core.domain.AjaxResult;
import com.rfid.common.utils.poi.ExcelUtil;
import com.rfid.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 产品信息Controller
 *
 * @author fangchen
 * @date 2020-12-08
 */
@Controller
@RequestMapping("/system/product")
public class TProductInfoController extends BaseController {
    private String prefix = "system/product";

    @Autowired
    private ITProductInfoService tProductInfoService;

    @Autowired
    private CodeGenerateService codeGenerateService;

    @Autowired
    private ITIteminfoService tIteminfoService;

    @Autowired
    private ITProductOrderTotalService itProductOrderTotalService;

    @RequiresPermissions("system:product:view")
    @GetMapping()
    public String product() {
        return prefix + "/product";
    }

    /**
     * 查询产品信息列表
     */
    @RequiresPermissions("system:product:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Long orderId,String uuids,TProductInfo TProductInfo) {
        startPage();
        System.out.println("orderId"+orderId);
        if(uuids==null){
            if(orderId==null){
                List<TProductInfo> list = tProductInfoService.selectTProductInfoList(TProductInfo);
                if(CollectionUtils.isNotEmpty(list)){
                    list.forEach(info->{
                        Long productId=info.getId();
                        TItemInfo tItemInfo=new TItemInfo();
                        tItemInfo.setProductInfoId(String.valueOf(productId));
                        List<TItemInfo> tItemInfoList=tIteminfoService.selectTIteminfoList(tItemInfo);
                        info.setItemNum(tItemInfoList.size());
                    });
                }
                return getDataTable(list);
            }else{
                List<TProductInfo> productInfosss=itProductOrderTotalService.selectByOrderNo(orderId);
                if(!CollectionUtils.isEmpty(productInfosss)){
                    if(productInfosss.get(0)==null){
                        productInfosss=new ArrayList<>();
                    }
                }
                return getDataTable(productInfosss);
            }
        }else{
            uuids=uuids.split(",")[0];
            List<TProductInfo> productInfos=null;
            if(orderId==null){
                //查询成品产品关联表
                productInfos= itProductOrderTotalService.selectByRemark(uuids);
                List<TProductInfo> productInfoss= new ArrayList<>();
                if(!CollectionUtils.isEmpty(productInfos)){
                    if(productInfos.get(0)==null){
                        productInfos=new ArrayList<>();
                    }
                }
            }else{
                productInfos=itProductOrderTotalService.selectByOrderId(uuids,orderId);
            }

            return getDataTable(productInfos);
        }
    }

    /**
     * 导出产品信息列表
     */
    @RequiresPermissions("system:product:export")
    @Log(title = "产品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TProductInfo TProductInfo) {
        List<TProductInfo> list = tProductInfoService.selectTProductInfoList(TProductInfo);
        ExcelUtil<TProductInfo> util = new ExcelUtil<TProductInfo>(TProductInfo.class);
        return util.exportExcel(list, "product");
    }

    /**
     * 新增产品信息
     */
    @GetMapping("/add")
    public String add(String type,Long uuids,Long orderId,ModelMap mmap) {
        if(type==null){
            return prefix + "/add";
        }else{
            mmap.put("uuids",uuids);
            mmap.put("orderId",orderId);
            return "system/total" + "/productAdd";
        }

    }

    /**
     * 新增保存产品信息
     */
    @RequiresPermissions("system:product:add")
    @Log(title = "产品信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TProductInfo tProductInfo) {
        TProductInfo lastData=tProductInfoService.getLastData();
        String productNo="";
        if(lastData!=null){
            productNo=codeGenerateService.generateCode("PRODUCT_CODE_RULE",lastData.getProductNo(),lastData);
        }else{
            productNo=codeGenerateService.generateCode("PRODUCT_CODE_RULE","",lastData);
        }

        if(StringUtils.isEmpty(productNo)){
            throw new BusinessException("生成产品编码不能为空");
        }
        if(StringUtils.isEmpty(tProductInfo.getProductName())){
            throw new BusinessException("产品名称不能为空");
        }
        TProductInfo queryCus=new TProductInfo();
        queryCus.setProductNo(productNo);
        List<TProductInfo> list=tProductInfoService.selectTProductInfoList(queryCus);
        if(CollectionUtils.isNotEmpty(list)){
            throw new BusinessException("生成产品编码重复");
        }
        queryCus=new TProductInfo();
        queryCus.setProductName(tProductInfo.getProductName());
        List<TProductInfo> list2=tProductInfoService.selectTProductInfoList(queryCus);
        if(CollectionUtils.isNotEmpty(list2)){
            throw new BusinessException("产品名称重复");
        }
        tProductInfo.setProductNo(productNo);
        tProductInfo.setCreateBy(ShiroUtils.getLoginName());
        tProductInfo.setUpdateBy(ShiroUtils.getLoginName());
        tProductInfo.setCreateTime(new Date());
        tProductInfo.setUpdateTime(new Date());
        tProductInfo.setLastSerialNum("0");
        tProductInfoService.insertTProductInfo(tProductInfo);
        return AjaxResult.success("生成的产品编号是"+tProductInfo.getProductNo());
    }

    /**
     * 新增保存产品信息
     */
    @RequiresPermissions("system:product:add")
    @Log(title = "产品信息", businessType = BusinessType.INSERT)
    @PostMapping("/addpro")
    @ResponseBody
    @Transactional
    public AjaxResult addpro(String orderId,TProductInfo tProductInfo) {
/*        TProductInfo lastData=tProductInfoService.getLastData();
        String productNo="";
        if(lastData!=null){
            productNo=codeGenerateService.generateCode("PRODUCT_CODE_RULE",lastData.getProductNo(),lastData);
        }else{
            productNo=codeGenerateService.generateCode("PRODUCT_CODE_RULE","",lastData);
        }

        if(StringUtils.isEmpty(productNo)){
            throw new BusinessException("生成产品编码不能为空");
        }
        if(StringUtils.isEmpty(tProductInfo.getProductName())){
            throw new BusinessException("产品名称不能为空");
        }
        TProductInfo queryCus=new TProductInfo();
        queryCus.setProductNo(productNo);
        List<TProductInfo> list=tProductInfoService.selectTProductInfoList(queryCus);
        if(CollectionUtils.isNotEmpty(list)){
            throw new BusinessException("生成产品编码重复");
        }
        queryCus=new TProductInfo();
        queryCus.setProductName(tProductInfo.getProductName());
        List<TProductInfo> list2=tProductInfoService.selectTProductInfoList(queryCus);
        if(CollectionUtils.isNotEmpty(list2)){
            throw new BusinessException("产品名称重复");
        }
        tProductInfo.setProductNo(productNo);
        tProductInfo.setCreateBy(ShiroUtils.getLoginName());
        tProductInfo.setUpdateBy(ShiroUtils.getLoginName());
        tProductInfo.setCreateTime(new Date());
        tProductInfo.setUpdateTime(new Date());
        tProductInfo.setLastSerialNum("0");
        tProductInfoService.insertTProductInfo(tProductInfo);*/
        //生成成品订单关联信息
        String remark= CacheUtils.get("uuid").toString();
        //通过uuid查询是否改成品已经添加改产品
        TProductOrderTotal queryTotal=new TProductOrderTotal();
        queryTotal.setProductId(tProductInfo.getId());
        queryTotal.setRemark(remark);
        TProductOrderTotal tProductOrderTotal=new TProductOrderTotal();
        List<TProductOrderTotal> tProductOrderTotals=itProductOrderTotalService.selectTProductOrderTotalList(queryTotal);
        if(!CollectionUtils.isEmpty(tProductOrderTotals)){
            return AjaxResult.warn("产品已添加");
        }
        if(!StringUtils.isEmpty(orderId)&&!orderId.equals(",")){
            orderId=orderId.split(",")[0];
            queryTotal.setOrderTotalId(Long.parseLong(orderId));
            tProductOrderTotals= itProductOrderTotalService.selectTProductOrderTotalList(queryTotal);
        }
        if(!CollectionUtils.isEmpty(tProductOrderTotals)){
            tProductOrderTotal=tProductOrderTotals.get(0);
            tProductOrderTotal.setField(tProductInfo.getProductNum());
            tProductOrderTotal.setUpdateTime(new Date());
            tProductOrderTotal.setUpdateBy(ShiroUtils.getLoginName());
            itProductOrderTotalService.updateTProductOrderTotal(tProductOrderTotal);
        }else{

            tProductOrderTotal.setRemark(remark);
            tProductOrderTotal.setProductId(tProductInfo.getId());
            tProductOrderTotal.setField(tProductInfo.getProductNum());
            tProductOrderTotal.setCreateBy(ShiroUtils.getLoginName());
            tProductOrderTotal.setUpdateBy(ShiroUtils.getLoginName());
            tProductOrderTotal.setCreateTime(new Date());
            tProductOrderTotal.setUpdateTime(new Date());
            itProductOrderTotalService.insertTProductOrderTotal(tProductOrderTotal);
        }
        return AjaxResult.success();
    }
    /**
     * 修改产品信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        TProductInfo TProductInfo = tProductInfoService.selectTProductInfoById(id);
        mmap.put("TProductInfo", TProductInfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存产品信息
     */
    @RequiresPermissions("system:product:edit")
    @Log(title = "产品信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TProductInfo TProductInfo) {
        return toAjax(tProductInfoService.updateTProductInfo(TProductInfo));
    }

    /**
     * 删除产品信息
     */
    @RequiresPermissions("system:product:remove")
    @Log(title = "产品信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids,String type) {
        if(type!=null){
            TProductOrderTotal tProductOrderTotal=new TProductOrderTotal();
            tProductOrderTotal.setProductId(Long.valueOf(ids));
            List<TProductOrderTotal> list=itProductOrderTotalService.selectTProductOrderTotalList(tProductOrderTotal);
            itProductOrderTotalService.deleteTProductOrderTotalById(list.get(0).getId());
            return toAjax(tProductInfoService.deleteTProductInfoByIds(ids));
        }else{
            TItemInfo tItemInfo=new TItemInfo();
            tItemInfo.setProductInfoId(String.valueOf(ids));
            List<TItemInfo> tItemInfoList=tIteminfoService.selectTIteminfoList(tItemInfo);
            if(CollectionUtils.isNotEmpty(tItemInfoList)){
                throw new BusinessException("成品已绑定产品信息,不能删除");
            }
            return toAjax(tProductInfoService.deleteTProductInfoByIds(ids));
        }
    }

    @RequiresPermissions("system:product:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<TProductInfo> util = new ExcelUtil<TProductInfo>(TProductInfo.class);
        return util.importTemplateExcel("产品数据");
    }


    /**
     * 导入产品数据
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "产品管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<TProductInfo> util = new ExcelUtil<TProductInfo>(TProductInfo.class);
        List<TProductInfo> cusList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = tProductInfoService.importUser(cusList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * @Author fangchen
     * @Description //产品信息查看
     * @Date 15:15 2020/12/16
     * @Param [operId, mmap]
     * @return java.lang.String
     **/
    @RequiresPermissions("system:product:detail")
    @GetMapping("/detail/{productId}")
    public String detail(@PathVariable("productId") Long productId, ModelMap mmap) {
        TProductInfo info = tProductInfoService.selectTProductInfoById(productId);
        TItemInfo tItemInfo=new TItemInfo();
        tItemInfo.setProductInfoId(String.valueOf(productId));
        List<TItemInfo> tItemInfoList=tIteminfoService.selectTIteminfoList(tItemInfo);
        if(CollectionUtils.isNotEmpty(tItemInfoList)){
            info.setItemNum(tItemInfoList.size());
        }else{
            info.setItemNum(0);
        }
        mmap.put("TProductInfo", info);
        return prefix + "/detail";
    }
}
